<template>
  <div>
    <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="创意类型" name="creativeType">
        <a-radio-group v-model:value="formState.creativeType">
          <a-radio-button :value="1044">富媒体</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="创意描述" name="description">
        <a-input v-model:value="formState.description" allowClear />
      </a-form-item>
      <a-form-item label="落地页" name="">
        <div>
          <a-button type="primary" @click="setLadingPageClick">设置落地页</a-button>
        </div>
        <div style="padding-top: 5px" v-if="getAccountCount() > 0">{{ getAccountCount() }}个账户已设置</div>
      </a-form-item>
    </a-form>
    <SetLadingPage ref="setLadingPageRef" @update:save="updateLadingPageMap" :key="key" />
  </div>
</template>

<script setup lang="ts">
import { ref, provide } from "vue";
import _ from "lodash";
import SetLadingPage from "@/pages/NewBatchCreateAd/adx/xiaomi/creativeConfig/SetLadingPage.vue";
import { message } from "ant-design-vue";
import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";

const store = batchCreateAdStore();

const formRef = ref();
const formState = ref({
  creativeType: 1044,
  description: "",
});

const key = ref(0);

const rules = {
  creativeType: [{ required: true, message: "" }],
  description: [{ required: true, message: "" }],
};

const setData = () => {
  const CreativeConfig: any = store.CreativeConfig || {};

  const obj: any = {
    creativeType: CreativeConfig.creativeType || 1044,
    description: CreativeConfig.description || "",
  };

  formState.value = obj;
};

// 选择落地页相关代码
const setLadingPageRef = ref();
const setLadingPageClick = () => {
  if (store.AccountItems.length === 0) {
    message.warning("请选择账号");
    return;
  }
  setLadingPageRef.value.show();
};

const ladingPage = ref(_.cloneDeep(store.CreativeConfig.ladingPageMap) || {});

provide("ladingPageMap", ladingPage);
const updateLadingPageMap = (ladingPageMap: any) => {
  ladingPage.value = ladingPageMap;
  setLadingPageRef.value.hide();
  key.value++;
};

const getAccountCount = () => {
  const ladingPageMap: any = ladingPage.value || {};
  return Object.keys(ladingPageMap).length;
};

// 表单校验方法
const validate = async () => {
  try {
    await formRef.value.validate();
  } catch (err: any) {
    // 滚动到第一个失败的字段
    formRef.value.scrollToField(err.errorFields[0].name[0]);
    return false;
  }
  return true;
};

// 导出给父组件使用的方法
const getData = () => {
  let obj: any = _.cloneDeep(formState.value);
  obj.ladingPageMap = ladingPage.value;
  return _.cloneDeep(obj);
};

defineExpose({
  setData,
  getData,
  validate,
});

const emit = defineEmits(["update:data"]);
</script>

<style scoped></style>
